package backend

import (
	models "awesomeProject1/models/pojo"
	"awesomeProject1/pkg/e"
	"awesomeProject1/pkg/gintool"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/simplechain-org/client/log"
	"strings"
	"time"
)

type AddP2pFailedDataReq struct {
	StartDate string `json:"startDate"` //格式：20230824
	EndDate   string `json:"endDate"`   //格式：20230824
}

//检查转账详情接口中的To参数是否正确
func (b *backend) checkDetailsParameter(ctx *gin.Context) {
	fnName := "checkDetailsParameter"
	req := new(AddP2pFailedDataReq)
	if err := ctx.Bind(req); err != nil {
		log.Error("params validate error:", "err", err.Error())
		gintool.ResultCodeWithData(ctx, e.InvalidParams, err.Error())
		return
	}

	hasEnd, startTime, endTime := parseDateRange(ctx, req.StartDate, req.EndDate)
	if hasEnd {
		return
	}

	//所有的详情上传数据
	allSendDetailsList, hasEnded := b.getAllSendDetailsList(ctx, startTime, endTime)
	if hasEnded {
		return
	}

	wrongCount := 0
	for _, sendDetails := range allSendDetailsList {
		log.Info(fnName, "正在检查：", sendDetails.ReceiptIDHash)
		//通过借据号哈希查询到此笔借据的放款信息
		firstLoanDetails, count, err := b.detailServ.GetFirstLoanDetailsByReceiptIdHash(sendDetails.ReceiptIDHash)
		if err != nil {
			log.Error(fnName, "callFn", "b.detailServ.GetFirstLoanDetailsByReceiptIdHash", "err", err.Error())
			gintool.ResultCodeWithData(ctx, e.InvalidParams, err.Error())
			return
		}
		if count > 1 {
			log.Warn(fnName, "hint", "通过receiptIdHash查询first_loan表，匹配到了多条数据", "FirstLoanDetails", firstLoanDetails)
		} else if len(firstLoanDetails) == 0 {
			log.Warn(fnName, "hint", "通过receiptIdHash查询first_loan表，未匹配到数据", "sendDetails", sendDetails.ReceiptIDHash)
			continue
		}

		expectedLoanBankId := firstLoanDetails[0].ParentBankId
		if !strings.Contains(sendDetails.To, expectedLoanBankId) {
			log.Warn(fnName, "hint", "详情转账的To不是期望的对象",
				"sendDetails.From", strings.ReplaceAll(sendDetails.From, "map", "FromMap"),
				"sendDetails.To", strings.ReplaceAll(sendDetails.To, "map", "ToMap"),
				"sendDetails.TransferDetails", sendDetails.TransferDetails,
				"sendDetails.ReceiptID", sendDetails.ReceiptID,
				"sendDetails.Date", sendDetails.Date,
				"FirstLoanDetails", firstLoanDetails)
			wrongCount++
		}
	}

	hint := fmt.Sprintln("总共检测详情笔数：", len(allSendDetailsList), "异常笔数", wrongCount)
	gintool.ResultCodeWithData(ctx, e.Ok, hint)
	gintool.ResultOk(ctx)
}

func (b *backend) getAllSendDetailsList(ctx *gin.Context, startTime, endTime time.Time) (sendDetailsList []models.UploadDetailsRecord, hasEnded bool) {
	log.Info("DBList", "total", len(b.conf.DBOnlineList))
	for _, v := range b.conf.DBOnlineList {
		log.Info("DBList", "bankName", v.BankName, "host", v.Host)
	}

	for i, engine := range b.dbOnlineList {
		list, total, code := b.detailServ.GetSendDetailsList(engine, startTime, endTime)
		if code != e.Ok {
			log.Error("获取详情上传备份数据错误", "errInfo", e.GetMsg(code), "bankConf", b.conf.DBOnlineList[i])
			gintool.ResultCode(ctx, code)
			hasEnded = true
			continue
		}
		log.Info("详情上传数据总数", "total", total, "bankName", b.conf.DBOnlineList[i].BankName)
		if len(list) == 0 {
			continue
		}

		if len(sendDetailsList)+len(list) > 100000000 {
			log.Error("获取详情上传备份数据过多", "total", total)
			hint := fmt.Sprintln("获取详情上传备份数据过多, total=", total)
			gintool.ResultCodeWithData(ctx, e.Error, hint)
			hasEnded = true
			return
		}
		sendDetailsList = append(sendDetailsList, list...)
	}
	return
}
